<?php

const ICON_WORK = '## ';
const ICON_OKAY = '(^ᴗ^) ';
const ICON_FAIL = '(◞‸◟) ';

function arrayMerge($a, $b)
{
    $args = func_get_args();
    $res = array_shift($args);
    while (!empty($args)) {
        foreach (array_shift($args) as $k => $v) {
            if (is_int($k)) {
                if (array_key_exists($k, $res)) {
                    $res[] = $v;
                } else {
                    $res[$k] = $v;
                }
            } elseif (is_array($v) && isset($res[$k]) && is_array($res[$k])) {
                $res[$k] = arrayMerge($res[$k], $v);
            } else {
                $res[$k] = $v;
            }
        }
    }
    return $res;
}

function setServerPid(string $pid)
{
    file_put_contents(RUNTIME . '/run/pid', $pid);
}

function getServerPid(): ?int
{
    return (int)@file_get_contents(RUNTIME . '/run/pid') ?: null;
}

function setRunConfig(array $config)
{
    @file_put_contents(RUNTIME . '/run/config', json_encode($config));
}

function getRunConfig()
{
    $configStr = @file_get_contents(RUNTIME . '/run/config');
    return json_decode($configStr, true);
}

function getWorkerNum(): int
{
    return (int)shell_exec("ps -ef | grep syncer | grep -v 'grep' | wc -l 2>&1");
}

function getStateStr(): string
{
    $pid = getServerPid();
    $workerNum = getWorkerNum();
    if ($workerNum && $pid) {
        $config = getRunConfig();
        $serverConfig = $config['server'];
        $stateStr = "| HttpServer %s:%d | workerNum: %d | processPid：%d |";
        return sprintf($stateStr, $serverConfig['host'], $serverConfig['port'], $workerNum, $pid);
    }
    die("!!当前程序未在运行" . PHP_EOL);
}
